"""
NLU (Natural Language Understanding) API路由
提供自然语言理解接口
"""

from fastapi import APIRouter, HTTPException, Form
from services.nlu import NLUService
from utils.logger import (
    emobot_logger,
    log_function_call,
    log_function_result,
    log_function_error,
)
from utils.performance_logger import (
    log_api_call,
    track_step
)
import time

logger = emobot_logger.get_logger()

router = APIRouter(prefix="/api/nlu", tags=["nlu"])


@router.post("/analyze")
async def analyze_task(
    text: str = Form(..., description="语音识别出的文本内容"),
    task_id: str = Form(..., description="唯一任务标识符,建议使用UUID格式"),
    robot_id: str = Form(..., description="端侧传输"),
    任务类型: str = Form(..., description="简单/隐私 or 复杂/非隐私")
):
    """
    自然语言理解接口
    
    Args:
        text: 语音识别出的文本内容
        task_id: 唯一任务标识符,建议使用UUID格式
        robot_id: 端侧传输
        任务类型: 简单/隐私 or 复杂/非隐私
        
    Returns:
        端侧响应 (JSON)
    """
    start_time = time.time()
    
    # 验证任务ID
    if not task_id or not task_id.strip():
        raise HTTPException(status_code=400, detail="任务ID不能为空")
    
    # 验证robot_id
    if not robot_id or not robot_id.strip():
        raise HTTPException(status_code=400, detail="robot_id不能为空")
    
    log_function_call("analyze_task", {
        "text": text[:100] + "..." if len(text) > 100 else text,
        "task_id": task_id,
        "robot_id": robot_id
    })
    
    emobot_logger.log_api_request(
        "POST", "/api/nlu/analyze", {
            "text_length": len(text),
            "task_id": task_id,
            "robot_id": robot_id
        }
    )
    
    try:
        # 验证输入
        if not text or not text.strip():
            raise HTTPException(status_code=400, detail="输入文本不能为空")
        
        # 调用NLU服务
        with track_step("NLU_ANALYSIS", {
            "task_id": task_id,
            "text_length": len(text)
        }):
            nlu_service = NLUService()
            result = await nlu_service.analyze_task(text, task_id, robot_id)
        
        # 记录API调用
        log_api_call(
            api_name="NLU_ANALYZE_API",
            api_type="HTTP",
            request_data={
                "task_id": task_id,
                "text_length": len(text),
                "robot_id": robot_id
            }
        )
        
        duration = (time.time() - start_time) * 1000
        
        # 构建端侧响应格式
        response = {
            "task_id": task_id,
            "robot_id": robot_id,
            "status": "success" if result.get("success", False) else "error",
            "endpoint_status": "online",
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "nlu_result": {
                "text": result.get("text", text),
                "任务类型": result.get("任务类型", "未知"),
                "confidence": result.get("confidence", 0.0),
                "reasoning": result.get("reasoning", "")
            }
        }
        
        if not result.get("success", False):
            response["status"] = "error"
            response["error"] = result.get("error", "NLU分析失败")
            emobot_logger.log_api_response(
                "POST", "/api/nlu/analyze", 500, response, duration
            )
            log_function_error("analyze_task", Exception(result.get("error", "NLU failed")), {
                "task_id": task_id,
                "text_length": len(text)
            })
            raise HTTPException(status_code=500, detail=result.get("error", "NLU分析失败"))
        
        emobot_logger.log_api_response(
            "POST", "/api/nlu/analyze", 200, response, duration
        )
        log_function_result("analyze_task", response, duration)
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"NLU分析失败: {e}")
        emobot_logger.log_api_response(
            "POST", "/api/nlu/analyze", 500, {"error": str(e)}, duration
        )
        log_function_error("analyze_task", e, {
            "task_id": task_id,
            "text_length": len(text)
        })
        raise HTTPException(status_code=500, detail=str(e))



